//
//  BillCardView.swift
//  Speek
//
//  Created by MikeHo on 2023/4/14.
//

import SwiftUI
import CoreData

struct BillCardView: View {
    let bill : BillDetail
    @Environment(\.managedObjectContext) private var context

    @State private var isShowEdit = false
    @State private var isEditing = false
    
    var body: some View {
        
            HStack(spacing:10){
                
                //账单种类图片
                Image(bill.type ?? "")
                    .resizable()
                    .frame(width: 60, height: 60)
                
                //账单的种类和日期
                VStack{
                    Text(bill.type ?? "")
                        .font(.subheadline)
                    Text(dateFormatter(date:(bill.date ?? .init())))
                        .font(.subheadline)
                }
                .padding(.horizontal,5)
                .frame(width: 60, height: 60)
                .foregroundColor(.white)
                
                //账单具体事件
                Text(bill.name ?? "")
                    .font(.headline)
                    .foregroundColor(.white)
                    .frame(width: 120)
                
                //账单金额和类型
                Text(getInOrOut(tag:bill.tag)+"¥"+String(bill.cost))
                    .frame(width: 100, height: 60)
                    .foregroundColor(bill.tag ? Color(red:0,green: 0.725,blue: 0.678):Color(red:1.0,green: 0.341,blue: 0.204))
                    .background(RoundedRectangle(cornerRadius: 10)
                        .stroke(bill.tag ? Color(red:0,green: 0.725,blue: 0.678).opacity(0.5):Color(red:1.0,green: 0.341,blue: 0.204).opacity(0.5), lineWidth: 2))
                    .frame(alignment: .trailing)
                
                //删除和编辑按钮
                if isShowEdit{
                    VStack(spacing: 10){
                        
                        //编辑账单按钮
                        Button(action: {
                            isEditing = true
                        }) {
                            Image(systemName: "square.and.pencil")
                                .aspectRatio(contentMode: .fit)
                                .foregroundColor(.green)
                        }
                        
                        //删除账单按钮
                        Button(action: {
                            deleteBillDetail(type: bill.type ?? "", date: bill.date ?? .init(), name: bill.name ?? "" ,cost:bill.cost)
                        }) {
                            Image(systemName: "trash")
                                .aspectRatio(contentMode: .fit)
                                .foregroundColor(.red)
                        }
                    }
                    .padding(.trailing,30)
                }
            }
            .frame(width: 390, height: 100)
            .background(Color(red:0.04,green: 0.09,blue: 0.16).cornerRadius(20))
            .preferredColorScheme(.dark)
            .gesture(SwipeToEdit)
            .onTapGesture {
                isShowEdit = false
            }
            .sheet(isPresented: $isEditing){
                DetailEdit(EditingBill: bill)
                    .presentationDetents([.large])
                    .presentationDragIndicator(.hidden)
                    .interactiveDismissDisabled()
                    .navigationBarTitle("",displayMode: .inline)
                
            }
            .clipped()
    }
    
    //从tag中获取金额显示的正负
    func getInOrOut(tag:Bool)->String{
        if tag {
            return "+"
        }else{
            return "-"
        }
    }
    
    //将日期格式化为“月-日”
    private func dateFormatter(date:Date)->String{
        let Formatter = DateFormatter()
        Formatter.dateFormat = "MM-dd"
        let formattedDate = Formatter.string(from: date)
        return formattedDate
    }
    
    //滑动显示删除/编辑键
    private var SwipeToEdit: some Gesture {
        DragGesture()
            .onEnded { gesture in
                if gesture.translation.width < 100 {
                    isShowEdit = true
                }
            }
    }
    
    //从CoreData中删除账单
    func deleteBillDetail(type: String, date: Date, name: String, cost:Double) {
        let fetchRequest: NSFetchRequest<BillDetail> = BillDetail.fetchRequest()
        let typePredicate = NSPredicate(format: "type == %@", type)
        let datePredicate = NSPredicate(format: "date == %@", date as NSDate)
        let namePredicate = NSPredicate(format: "name == %@", name)
        _ = NSPredicate(format: "cost == %@", NSNumber(value: cost))
        
        let compoundPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [typePredicate, datePredicate, namePredicate])
         fetchRequest.predicate = compoundPredicate
        do {
            let fetchedResults = try context.fetch(fetchRequest)
            if let billDetail = fetchedResults.first {
                context.delete(billDetail)
                print("删除启动")
                try context.save()
                // 删除成功
            }
        } catch {
            // 处理错误
            print("Error deleting bill detail: \(error)")
        }
    }

}

struct BillCardView_Previews: PreviewProvider {
 
    
    static var previews: some View {
        
            SecondView()
    }
}

